<template>
  <div class="about">
    <!-- 头部 -->
    <van-nav-bar
    title="上传分数系统"
    left-text="返回"
    @click-left="$router.back()"
   
    />
    <!-- 表单 -->
    <van-form @submit="onSubmit">
  <van-cell-group inset>
    <van-field  
      v-model="form.user"
      name="姓名"
      label="姓名"
      placeholder="姓名"
      :rules="[{ required: true, message: '请填写姓名' }]"
    />
    <van-field
      v-model="form.theory"
      name="理论成绩"
      label="理论成绩"
      placeholder="理论成绩"
      :rules="[{ required: true, message: '请填写理论成绩' },{pattern,message: '请填写0-100的数'}]"
    />
     <van-field
      v-model="form.skill"
      name="技能成绩"
      label="技能成绩"
      placeholder="技能成绩"
      :rules="[{ required: true, message: '请填写技能成绩' },{pattern,message: '请填写0-100的数'}]"
    />
  </van-cell-group>
  <div style="margin: 16px;">
    <van-button round block type="primary" native-type="submit">
      {{index?'编辑':'添加'}}
    </van-button>
  </div>
</van-form>

  </div>
</template>
<script>
import {reactive,toRefs,computed} from 'vue'
import {useStore} from 'vuex'
import {useRouter,useRoute} from 'vue-router'

export default {
    setup(){
        const {state,commit} = useStore()
        const {push} = useRouter()
        const route = useRoute()
        const index = route.query.index

        const data = reactive({
            form:{
                user:"",
                theory:"",
                skill:""

            }
            // 0-100的正则
            // 在正则里面?
            
        })

        const pattern = /^(([1-9][0-9]?)|100|100.00|0)$/
        const  list = computed(()=>state.gradesList)

    
  
        // 回显数据
        index && (data.form = state.gradesList[index])

        // 添加
        const onSubmit=()=>{
           if(index){
               commit('edit',{index:index,form:data.form})
                push('/')

           }else{
                 // 判重
                let flag = state.gradesList.some(item=>item.user==data.form.user)
                if(flag){
                    alert('重复')
                    return
                }
                //  添加数据
                commit('add',data.form)
                push('/')
           }
       
        }
        return {...toRefs(data),pattern,list,onSubmit,index}
    }
}
</script>
